package com.example.mydy;

import com.example.mydy.model.RewardTask;
import com.example.mydy.model.User;
import com.example.mydy.model.UserData;
import com.example.mydy.model.UserListResponse;
import com.example.mydy.model.Advertisement;
import com.example.mydy.model.Announcement;
import com.example.mydy.model.AnnouncementListResponse;
import com.example.mydy.model.AdvertisementListResponse;
import com.example.mydy.model.Project;
import com.example.mydy.model.ProjectListResponse;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.NetworkUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 模拟API服务类，用于在不连接实际服务器的情况下模拟API响应
 */
public class MockApiService {
    
    /**
     * 模拟获取所有悬赏任务
     */
    public static void getRewardTasks(Callback<List<RewardTask>> callback) {
        List<RewardTask> rewardTasks = MockDataManager.getInstance().getAllRewardTasks();
        callback.onResponse(null, Response.success(rewardTasks));
    }
    
    /**
     * 模拟获取单个悬赏任务
     */
    public static void getRewardTask(int taskId, Callback<RewardTask> callback) {
        RewardTask task = MockDataManager.getInstance().getRewardTaskById(taskId);
        if (task != null) {
            callback.onResponse(null, Response.success(task));
        } else {
            callback.onFailure(null, new Exception("Task not found"));
        }
    }
    
    /**
     * 模拟接受悬赏任务
     */
    public static void takeRewardTask(String username, int taskId, Callback<CommonResponse> callback) {
        CommonResponse response = new CommonResponse();
        
        boolean success = MockDataManager.getInstance().takeRewardTask(username, taskId);
        if (success) {
            response.setSuccess(true);
            response.setMessage("任务接受成功");
            callback.onResponse(null, Response.success(response));
        } else {
            response.setSuccess(false);
            response.setMessage("接受任务失败，该任务可能已被接取或已满额");
            callback.onResponse(null, Response.success(response));
        }
    }
    
    /**
     * 模拟获取用户数据
     */
    public static void getUserData(String username, Callback<UserData> callback) {
        UserData userData = MockDataManager.getInstance().getUserData(username);
        if (userData != null) {
            callback.onResponse(null, Response.success(userData));
        } else {
            // 如果找不到用户，创建一个默认用户
            UserData defaultUser = new UserData();
            defaultUser.setUsername(username);
            defaultUser.setBalance(100.0);
            defaultUser.setLevel("新用户");
            callback.onResponse(null, Response.success(defaultUser));
        }
    }
    
    /**
     * 模拟用户登录
     */
    public static void login(String username, String password, Callback<LoginResponse> callback) {
        LoginResponse response = new LoginResponse();
        
        boolean success = NetworkUtils.mockLogin(username, password);
        if (success) {
            response.setSuccess(true);
            response.setMessage("登录成功");
            response.setToken("mock_token_" + System.currentTimeMillis());
            response.setUserType(NetworkUtils.getUserType());
            response.setUsername(username);
            
            // 设置用户ID，普通用户为1，管理员为99
            if ("admin".equals(NetworkUtils.getUserType())) {
                response.setUserId(99);
                response.setUserNickname("管理员");
            } else {
                response.setUserId(1);
                response.setUserNickname("测试用户");
            }
            
            // 设置用户余额和等级
            response.setBalance(1000.0);
            response.setLevel("普通会员");
            
            callback.onResponse(null, Response.success(response));
        } else {
            response.setSuccess(false);
            response.setMessage("用户名或密码错误，请使用test_user或admin作为用户名");
            callback.onResponse(null, Response.success(response));
        }
    }
    
    /**
     * 模拟获取所有用户（管理员功能）
     */
    public static void getUsers(Callback<UserListResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            UserListResponse errorResponse = new UserListResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        List<UserData> userDataList = MockDataManager.getInstance().getAllUsers();
        List<User> users = new ArrayList<>();
        
        // 将UserData对象转换为User对象
        for (UserData userData : userDataList) {
            users.add(User.fromUserData(userData));
        }
        
        UserListResponse response = new UserListResponse();
        response.setSuccess(true);
        response.setUsers(users);
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟获取单个用户信息（管理员功能）
     */
    public static void getUserById(int userId, Callback<User> callback) {
        if (!NetworkUtils.isAdmin()) {
            callback.onFailure(null, new Exception("没有权限访问此功能"));
            return;
        }
        
        List<UserData> allUsers = MockDataManager.getInstance().getAllUsers();
        for (UserData userData : allUsers) {
            // 假设UserData的username就是userId
            if (String.valueOf(userId).equals(userData.getUsername())) {
                User user = User.fromUserData(userData);
                callback.onResponse(null, Response.success(user));
                return;
            }
        }
        
        callback.onFailure(null, new Exception("用户不存在"));
    }
    
    /**
     * 模拟添加用户（管理员功能）
     */
    public static void addUser(UserData userData, String role, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().addUser(userData, role);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("用户添加成功");
        } else {
            response.setSuccess(false);
            response.setMessage("用户添加失败，可能用户名已存在");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟更新用户（管理员功能）
     */
    public static void updateUser(UserData userData, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().updateUser(userData);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("用户更新成功");
        } else {
            response.setSuccess(false);
            response.setMessage("用户更新失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟删除用户（管理员功能）
     */
    public static void deleteUser(String username, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().deleteUser(username);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("用户删除成功");
        } else {
            response.setSuccess(false);
            response.setMessage("用户删除失败，管理员用户不能被删除");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟获取广告列表（管理员功能）
     */
    public static void getAdvertisements(Callback<AdvertisementListResponse> callback) {
        List<Advertisement> ads = MockDataManager.getInstance().getAllAdvertisements();
        
        AdvertisementListResponse response = new AdvertisementListResponse();
        response.setSuccess(true);
        response.setAdvertisements(ads);
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟根据ID获取广告（管理员功能）
     */
    public static void getAdvertisementById(int adId, Callback<Advertisement> callback) {
        Advertisement ad = MockDataManager.getInstance().getAdvertisementById(adId);
        
        if (ad != null) {
            callback.onResponse(null, Response.success(ad));
        } else {
            callback.onFailure(null, new Exception("广告不存在"));
        }
    }
    
    /**
     * 模拟添加广告（管理员功能）
     */
    public static void addAdvertisement(Advertisement ad, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().addAdvertisement(ad);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("广告添加成功");
        } else {
            response.setSuccess(false);
            response.setMessage("广告添加失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟更新广告（管理员功能）
     */
    public static void updateAdvertisement(Advertisement ad, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().updateAdvertisement(ad);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("广告更新成功");
        } else {
            response.setSuccess(false);
            response.setMessage("广告更新失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟删除广告（管理员功能）
     */
    public static void deleteAdvertisement(int adId, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().deleteAdvertisement(adId);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("广告删除成功");
        } else {
            response.setSuccess(false);
            response.setMessage("广告删除失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟获取公告列表（管理员功能）
     */
    public static void getAnnouncements(Callback<AnnouncementListResponse> callback) {
        List<Announcement> announcements = MockDataManager.getInstance().getAllAnnouncements();
        
        AnnouncementListResponse response = new AnnouncementListResponse();
        response.setSuccess(true);
        response.setAnnouncements(announcements);
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟根据ID获取公告（管理员功能）
     */
    public static void getAnnouncementById(int id, Callback<Announcement> callback) {
        Announcement announcement = MockDataManager.getInstance().getAnnouncementById(id);
        
        if (announcement != null) {
            callback.onResponse(null, Response.success(announcement));
        } else {
            callback.onFailure(null, new Exception("公告不存在"));
        }
    }
    
    /**
     * 模拟添加公告（管理员功能）
     */
    public static void addAnnouncement(Announcement announcement, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().addAnnouncement(announcement);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("公告添加成功");
        } else {
            response.setSuccess(false);
            response.setMessage("公告添加失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟更新公告（管理员功能）
     */
    public static void updateAnnouncement(Announcement announcement, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().updateAnnouncement(announcement);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("公告更新成功");
        } else {
            response.setSuccess(false);
            response.setMessage("公告更新失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟删除公告（管理员功能）
     */
    public static void deleteAnnouncement(int id, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().deleteAnnouncement(id);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("公告删除成功");
        } else {
            response.setSuccess(false);
            response.setMessage("公告删除失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟获取项目列表（管理员功能）
     */
    public static void getProjects(Callback<ProjectListResponse> callback) {
        List<Project> projects = MockDataManager.getInstance().getAllProjects();
        
        ProjectListResponse response = new ProjectListResponse();
        response.setSuccess(true);
        response.setProjects(projects);
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟根据ID获取项目（管理员功能）
     */
    public static void getProjectById(int id, Callback<Project> callback) {
        Project project = MockDataManager.getInstance().getProjectById(id);
        
        if (project != null) {
            callback.onResponse(null, Response.success(project));
        } else {
            callback.onFailure(null, new Exception("项目不存在"));
        }
    }
    
    /**
     * 模拟添加项目（管理员功能）
     */
    public static void addProject(Project project, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().addProject(project);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("项目添加成功");
        } else {
            response.setSuccess(false);
            response.setMessage("项目添加失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟更新项目（管理员功能）
     */
    public static void updateProject(Project project, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().updateProject(project);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("项目更新成功");
        } else {
            response.setSuccess(false);
            response.setMessage("项目更新失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟删除项目（管理员功能）
     */
    public static void deleteProject(int id, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        boolean success = MockDataManager.getInstance().deleteProject(id);
        
        CommonResponse response = new CommonResponse();
        if (success) {
            response.setSuccess(true);
            response.setMessage("项目删除成功");
        } else {
            response.setSuccess(false);
            response.setMessage("项目删除失败");
        }
        
        callback.onResponse(null, Response.success(response));
    }
    
    /**
     * 模拟发布悬赏任务（管理员功能）
     */
    public static void publishReward(Map<String, Object> rewardData, Callback<CommonResponse> callback) {
        if (!NetworkUtils.isAdmin()) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("没有权限访问此功能");
            callback.onResponse(null, Response.success(errorResponse));
            return;
        }
        
        try {
            RewardTask newTask = new RewardTask();
            newTask.setTitle((String) rewardData.get("title"));
            newTask.setDescription((String) rewardData.get("description"));
            
            // 尝试获取奖励金额
            Object rewardObj = rewardData.get("reward");
            double reward = 0;
            if (rewardObj instanceof Number) {
                reward = ((Number) rewardObj).doubleValue();
            } else if (rewardObj instanceof String) {
                reward = Double.parseDouble((String) rewardObj);
            }
            newTask.setReward(reward);
            
            newTask.setTaken(false);
            newTask.setCreatedAt(java.time.LocalDateTime.now().toString());
            
            // 尝试获取截止日期
            String deadline = (String) rewardData.get("deadline");
            if (deadline != null) {
                newTask.setDeadline(deadline);
            } else {
                // 设置默认截止日期为30天后
                newTask.setDeadline(java.time.LocalDateTime.now().plusDays(30).toString());
            }
            
            // 设置默认剩余名额
            newTask.setRemainingOrders(10);
            newTask.setEarnedPeople(0);
            
            boolean success = MockDataManager.getInstance().addRewardTask(newTask);
            
            CommonResponse response = new CommonResponse();
            if (success) {
                response.setSuccess(true);
                response.setMessage("悬赏任务发布成功");
            } else {
                response.setSuccess(false);
                response.setMessage("悬赏任务发布失败");
            }
            callback.onResponse(null, Response.success(response));
        } catch (Exception e) {
            CommonResponse errorResponse = new CommonResponse();
            errorResponse.setSuccess(false);
            errorResponse.setMessage("发布任务时出错: " + e.getMessage());
            callback.onResponse(null, Response.success(errorResponse));
        }
    }
} 